package com.hzit.pay.center.service.strategy.impl;

import com.alibaba.fastjson.JSONObject;
import com.hzit.pay.center.config.PayCenterConfig;
import com.hzit.pay.center.exception.BizException;
import com.hzit.pay.center.factory.PayStrategyFactory;
import com.hzit.pay.center.model.PaySerialNoInfo;
import com.hzit.pay.center.service.strategy.IPaymentService;
import com.pay.center.common.enums.PayMethodEnum;
import com.pay.center.common.resp.RespPayData;
import com.pay.center.common.resp.Response;
import com.pay.center.common.utils.WXPayConstants;
import com.pay.center.common.utils.WXPayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 微信扫码支付
 */
@Service
public class WechatQrCodePayServiceImpl implements IPaymentService, InitializingBean {


    @Autowired
    private PayCenterConfig payCenterConfig;


    @Autowired
    private RestTemplate restTemplate;



    private Logger logger = LoggerFactory.getLogger(WechatQrCodePayServiceImpl.class);


    @Override
    public void afterPropertiesSet() throws Exception {

        PayStrategyFactory.concurrentHashMap.put(PayMethodEnum.WECHAT_QRCODE_PAY.getCode(),this);


    }

    @Override
    public Response<RespPayData> payment(PaySerialNoInfo paySerialNoInfo, String respKey) {
        //细节。对接微信支付接口

        //v2版本， xml

        Map<String,String> map = new HashMap<String,String>();
        map.put("appid",""); //微信支付分配的公众账号ID（企业号corpid即为此appId）
        map.put("mch_id","");  //微信支付分配的商户号
        map.put("nonce_str", UUID.randomUUID().toString().replace("-",""));

        map.put("body",paySerialNoInfo.getGoodsDesc());

        map.put("out_trade_no",paySerialNoInfo.getPaySerialNumber());
        map.put("total_fee",paySerialNoInfo.getPayAmount().toString());

        //服务端ip
        try {
            String ip = InetAddress.getLocalHost().getHostAddress();

            map.put("spbill_create_ip",ip);

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        map.put("notify_url",payCenterConfig.getNotifyUrl());

        map.put("trade_type","NATIVE");



        //#########可控#####
        map.put("device_info","");  //
        map.put("detail",paySerialNoInfo.getOrderDesc());
        map.put("attach","");
        map.put("fee_type","");
        map.put("time_start","");
        map.put("time_expire","");
        map.put("goods_tag","");
        map.put("product_id","");
        map.put("limit_pay","");
        map.put("openid","");
        map.put("receipt","");
        map.put("profit_sharing","");
        map.put("scene_info","");

        Response<RespPayData> response = new Response<RespPayData>();

        try {
            //获取到带有签名的xml格式
            String xmlStr = WXPayUtil.generateSignedXml(map,payCenterConfig.getWechatKey(), WXPayConstants.SignType.MD5);
            logger.info("请求报文：{}",xmlStr);

            //发送请求 https://api.mch.weixin.qq.com/pay/unifiedorder

            String respXml = restTemplate.postForObject(payCenterConfig.getWechatServiceUrl(),xmlStr,String.class);

            //<xml>
            //   <return_code><![CDATA[SUCCESS]]></return_code>
            //   <return_msg><![CDATA[OK]]></return_msg>
            //   <appid><![CDATA[wx2421b1c4370ec43b]]></appid>
            //   <mch_id><![CDATA[10000100]]></mch_id>
            //   <nonce_str><![CDATA[IITRi8Iabbblz1Jc]]></nonce_str>
            //   <openid><![CDATA[oUpF8uMuAJO_M2pxb1Q9zNjWeS6o]]></openid>
            //   <sign><![CDATA[7921E432F65EB8ED0CE9755F0E86D72F]]></sign>
            //   <result_code><![CDATA[SUCCESS]]></result_code>
            //   <prepay_id><![CDATA[wx201411101639507cbf6ffd8b0779950874]]></prepay_id>
            //   <trade_type><![CDATA[JSAPI]]></trade_type>
            //</xml>

           Map respMap = WXPayUtil.xmlToMap(respXml);

            if("SUCCESS".equalsIgnoreCase(String.valueOf(respMap.get("return_code")))
                   && "SUCCESS".equalsIgnoreCase(String.valueOf(respMap.get("result_code")))){

               String qrCode = respMap.get("code_url").toString();
               //Response<RespPayData> 对象方法

                RespPayData respPayData = new RespPayData();
                //生成内部签名
                respPayData.setPayUrl(qrCode);
               return response;

           }
            String msg =String.valueOf(respMap.get("return_msg"));

            response.setCode(-1);
            response.setMsg(msg);
            return response;
        } catch (Exception e) {
           logger.error("Exception",e);
            response.setCode(-1);
            response.setMsg(e.getMessage());
            return response;
        }
    }
}
